package com.edgelight.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;

@Component
public class MailTools {

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    CheckcodeTools checkcodeTools;

    @Value("${spring.mail.username}")
    private String from;

    public ResultMsg sendMail(String email, HttpSession session){
        System.out.println(email);
        ResultMsg resultMsg=new ResultMsg();
        try {
            //邮件发送的主体
            SimpleMailMessage message = new SimpleMailMessage();
            //邮件发送者
            message.setFrom(from);
            //接收者
            message.setTo(email);
            //邮件的标题
            message.setSubject("验证码");
            //邮件的内容
            System.out.println("----------");
            String code=checkcodeTools.getCode(4);
            System.out.println(code);
            message.setText(code);//发送验证码
            //同时存入session中
            session.setAttribute("checkcode",code);
            javaMailSender.send(message);
            resultMsg.setCode(200);
        }catch(Exception e){
            resultMsg.setCode(201);
        }
        return resultMsg;
    }
}
